<template>
    <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="搜索广告组"
        style="width: 220px;"
        class="filter-item"
      />

      <el-select
        v-model="listQuery.pkg"
        style="width: 150px"
        class="filter-item"
        filterable
        placeholder="请选择包"
        @change="handleFilter"
      >
        <el-option v-for="(v, k) in pkgs" :key="k" :label="v" :value="k" />
      </el-select>

      <el-select
        v-model="listQuery.brand"
        style="width: 150px"
        class="filter-item"
        filterable
        placeholder="请选择厂商"
        @change="handleFilter"
      >
        <el-option v-for="(v, k) in brand1" :key="k" :label="v" :value="k" />
      </el-select>

      <el-select
        v-model="listQuery.bidding_type"
        style="width: 150px"
        class="filter-item"
        filterable
        placeholder="选择广告类型"
        @change="handleFilter"
      >
        <el-option v-for="(v, k ) in adv_type" :key="k" :label="v" :value="k" />
      </el-select>

      <el-select
        v-model="listQuery.status"
        style="width: 150px"
        class="filter-item"
        placeholder="选择广告状态"
        @change="handleFilter"
      >
        <el-option key="2" label="已停用" value="0" />
        <el-option key="1" label="已启用" value="1" />
      </el-select>

      <el-button
       plain size="small"
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
       plain size="small"
        v-waves
        class="filter-item btn"
        type="primary"
        icon="el-icon-refresh"
        @click="handleCancel"
      >重置</el-button>
      <el-button
       plain size="small"
        v-waves
        class="filter-item btn"
        type="success"
        icon="el-icon-plus"
        @click="handleAdd()"
      >添加广告组</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
    <el-table-column label="软件名称" min-width="100" align="center" >
        <template slot-scope="{row}">
          <span>{{ row.pkg_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="厂商名称" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.brand }}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告组名称" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="广告类型" align="center">
        <template slot-scope="{row}">
          <span>{{ adv_type[row.bidding_type] }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="ecpm" min-width="100" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ecpm }}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告id" min-width="100" align="center">
        <template slot-scope="{row}">
          <span v-html="formateIdList(row.idList)"></span>
        </template>
      </el-table-column>   
      <el-table-column label="状态" min-width="100" align="center">
        <template slot-scope="{row}">
          <el-switch
            active-text="开启"
            inactive-text="关闭"
            v-model="row.status"
            :active-value="'1'"
            :inactive-value="'0'"
            @change="changeStatus(row,'status')"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        min-width="100"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button type="primary" plain size="small" @click="handleUpdate(row)">编辑</el-button>
          <!-- <el-button type="danger" plain size="small" @click="handleDel(row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      class="pageShow"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
<!-- 弹窗 -->
    <el-dialog
      title="sad"
      :visible.sync="updated"
      :width="dialogWidth"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="120px"
        class="fullwidth"
        enctype="multipart/form-data"
      >
        <el-form-item label="包" prop="adv_id">
          <el-select v-model="temp.adv_id" placeholder="请选择广告所属包">
            <el-option
              v-for="item in adv_config_list"
              :key="item.adv_id"
              :label="item.name + '---' + item.brand "
              :value="item.adv_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="广告组名称" prop="name">
          <el-input
            v-model.trim="temp.name"
            placeholder="使用 包名-序列"
          />
        </el-form-item>

        <el-form-item label="广告类型" prop="bidding_type">
          <el-select  v-model="temp.bidding_type" placeholder="广告类型" >
            <el-option
              v-for="(v,k ) in adv_type"
              :key="k"
              :label="v"
              :value="k">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="ecpm">
          <el-input v-model.number="temp.ecpm" placeholder="ecpm" />
        </el-form-item>

        <h2>广告id列表</h2>
        
        <el-row v-for="(value, index) in temp.idList" :key="index">
          <el-col :span="9"><div class="">

            <el-form-item label="id"  label-width="40px" :key="index"
              :prop="'idList[' + index + '].id'"
              :rules="{required: true, message: '广告的id不能为空', trigger: 'blur'}"
            >
              <el-input v-model.trim="value.id" placeholder="id" />

            </el-form-item>

          </div></el-col>
          <el-col :span="11"><div class="">

            <el-form-item label="advertId"  label-width="80px":key="index"
              :prop="'idList[' + index + '].advertId'"
              :rules="{required: true, message: '广告的advertId不能为空', trigger: 'blur'}"
            >
              <el-input v-model.trim="value.advertId" placeholder="id" />
            </el-form-item>
            
          </div></el-col>
          <el-col :span="4"><div class="" style="line-height: 40px;">
            <el-button style="margin-left: 20px;" @click="delidList(index)" icon="el-icon-minus" circle size="mini"></el-button>
          </div></el-col>
        </el-row>
        <el-button  @click="addAdvId" icon="el-icon-plus" circle ></el-button>

        <el-form-item label="状态" prop="status">
            <el-radio-group v-model="temp.status">
                <el-radio label="1">开启</el-radio>
                <el-radio label="0">关闭</el-radio>
            </el-radio-group>
        </el-form-item>

        <div style="text-align: right">
          <el-button plain size="small" @click="updated = false">取消</el-button>
          <el-button
           plain size="small"
            type="primary"
            :loading='addloading'
            @click="dialogStatus==='create'?handadd():handupdate()"
          >确定</el-button>
        </div>
      </el-form>
    </el-dialog>

  </div>
</template>
<script>
import { getAdvConfig, getAdvId,createAdvId, updateAdvId, getPkgList} from "@/api/adv_admin/config.js"
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import { Message, MessageBox } from "element-ui";
import { adv_type, brand1, advertisingType } from '@/utils/index.js'
export default {
    'name': 'LandingPage',
    components: { Pagination },
    directives: { waves },
    data() {
        return { 
          brand1,
          adv_type,
            def_ad:{
              adv_id:null,
              name: "",
              bidding_type: "",
              ecpm: 0,
              idList: [
                {
                  id: null,
                  advertId:null
                }
              ],
              status:'1'
            },
            tableKey: 0,
            listLoading: false,
            addloading: false,
            dialogWidth: '0px',
            list: [],
            total: 0,
            listQuery: {
                page: 1,
                limit: 20,
                bidding_type: "",
                name: "",
                status: "1",
            },
            rules: {
                adv_id: [
                    { required: true, message: "必填", trigger: "blur" }
                ],
                name: [
                    { required: true, message: "必填", trigger: "blur" }
                ],
                bidding_type: [
                    { required: true, message: "必选", trigger: "blur" }
                ],
                ecpm: [
                    { required: true, message: "必选", trigger: "blur" }
                ],
                status: [
                    { required: true, message: "必选", trigger: "blur" }
                ]
            },
            updated: false,
            update: '',
            dialogStatus: '',
            temp: {},
            adv_config_list: [],
            pkgs: {}
        }
    },
    created(){
      this.temp = JSON.parse(JSON.stringify(this.def_ad))
    },
    mounted(){
        this.getPkgs()
        this.getAdConfig()
        // this.getList()
        this.setDialogWidth()
    },
    methods: {
        setDialogWidth() {
            const val = document.body.clientWidth;
            const def = 600; // 默认宽度
            if (val < def) {
                this.dialogWidth = "100%";
            } else {
                this.dialogWidth = def + "px";
            }
        },
        getPkgs(){
          getPkgList().then(res => {
            if (res.STATUS == 200){
                    this.pkgs = res.DATA.list
                }
          })
        },
        getAdConfig(){
          getAdvConfig({status: "1"}).then(res => {
                if (res.STATUS == 200){
                    this.adv_config_list = res.DATA.list
                }
            })
        },
        getList(){
            this.listLoading = true
            getAdvId(this.listQuery).then(res => {
                if (res.STATUS == 200){
                    this.list = res.DATA.list
                    this.total = res.DATA.total
                }
                this.listLoading = false
            })
        },
        handleFilter() {
            this.listQuery.page = 1;
            this.getList();
        },
        handleCancel() {
            this.listQuery.page = 1;
            this.listQuery.name = "";
            this.listQuery.status = "";
            this.listQuery.pkg = "";
            this.listQuery.brand = "";
            this.listQuery.bidding_type = "";
            this.getList();
        },
        handleUpdate(row){
            this.updated = true
            this.temp =JSON.parse(JSON.stringify(row))  
            this.dialogStatus = 'update'
        },
        handleAdd(){
            this.updated = true
            this.temp = JSON.parse(JSON.stringify(this.def_ad))
            this.dialogStatus = 'create'
        },
        handadd(){
            this.addloading = true
            this.$refs['dataForm'].validate((valid) => {
            if (valid) {
                let data = JSON.parse(JSON.stringify(this.temp)) 
                data['advertising_type'] = advertisingType[data.bidding_type]
                data.idList = JSON.stringify(data.idList)

                createAdvId(data).then(res => {
                    if (res.STATUS == 200){
                        Message.success('添加成功')
                        this.updated = false
                        this.getList()
                    }else{
                        
                        Message({
                            message: res.DEC,
                            type: "error",
                            duration: 2000,
                        });
                        // Message.error()
                    }
                    this.addloading = false
                })

            } else {
                console.log('error submit!!');
                this.addloading = false
            }
            });
            // console.log(this.temp)
            
        },
        handupdate(){
            this.addloading = true
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    let data = JSON.parse(JSON.stringify(this.temp)) 
                    data['advertising_type'] = advertisingType[data.bidding_type]
                    data.idList = JSON.stringify(data.idList)
                    updateAdvId(data).then(res => {
                        if (res.STATUS == 200){
                            Message.success('修改成功')
                            this.updated = false
                            this.getList()
                        }else{
                            
                            Message({
                                message: res.DEC,
                                type: "error",
                                duration: 2000,
                            });
                            // Message.error()
                        }
                        this.addloading = false
                        
                    })
                } else {
                    this.addloading = false
                }
            });
        },
        changeStatus(item){
            let data = JSON.parse(JSON.stringify(item)) 
            data['advertising_type'] = advertisingType[data.bidding_type]
            data.idList = JSON.stringify(data.idList)
            updateAdvId(data).then(res => {
                if (res.STATUS == 200){
                    Message.success('修改成功')
                    this.updated = false
                    
                }else{
                    
                    Message({
                        message: res.DEC,
                        type: "error",
                        duration: 2000,
                    });
                    this.getList()
                }
            })
        },
        addAdvId(){
          this.temp.idList.push({
            id: null,
            advertId: null
          })
        },
        delidList(index){
          this.temp.idList.splice(index, 1)
        },
        formateIdList(list){
          let str = '';
          for(let i in list){
            str += list[i].id+":"+list[i].advertId + '<br/>' 
          }
          return str;
        }
    }
}
</script>
<style lang="scss" scoped>
.show-pwd {
  position: absolute;
  right: 10px;
  top: 0;
  font-size: 16px;
  color: #ccc;
  cursor: pointer;
  user-select: none;
}
.push {
  display: inline-block;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  margin-left: 5px;
}
.pageHidden {
  display: none;
}
.btn {
  margin-left: 0;
}
.fullwidth {
  width: 450px;
  margin-left: 50px;
}
@media (max-width: 550px) {
  .pageShow {
    display: none;
  }
  .pageHidden {
    display: block;
  }
  .fullwidth {
    width: 100%;
    margin-left: 0;
  }
}

.order_1{
  padding: 2px;
  border-radius: 4px;
  border: 2px solid #409EFF;
}
.order_2{
    padding: 2px;
  border-radius: 4px;
  border: 2px solid #7e7d7d;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 330px;
    /* height: 180px; */
    /* line-height: 178px; */
    text-align: center;
  }
  .avatar {
    width: 330px;
    /* height: 178px; */
    display: block;
  }
  .el-row {
    margin-bottom: 0px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
</style>